%%%-------------------------------------------------------------------
%%% @author root
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 二月 2016 下午8:52
%%%-------------------------------------------------------------------
-module(ks3_gif_handler).
-behaviour(cowboy_http_handler).

-include("cus.hrl").

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).




init(_Type, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  {Method,_} = cowboy_req:method(Req),
  HasBody = cowboy_req:has_body(Req),
  {CookieVal, Req2} = cowboy_req:cookie(<<"sessionid">>, Req),
%%  check SessionID and refresh cookie
  case cus_util:filter(CookieVal) of
    {true,UserName, PassWord} ->
      SessionID = cus_util:get_session_id(UserName,PassWord),
      Req3 = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, [
        {max_age, ?COOKIE_TIME}
      ], Req2),
      {ok,Req4} = maybe_echo(Method, HasBody, Req3),
      {ok, Req4, State};
    _->
      {ok, Body} = login_dtl:render([
      ]),
      {ok,Req3} = echo(Body, Req2),
      {ok, Req3, State}
  end.

terminate(_Reason, _Req, _State) ->
  ok.

maybe_echo(<<"GET">>, false, Req) ->
  DateTime = ?before(calendar:local_time(),3),
  Expiration=?b2l(cus_util:format_iso8601(DateTime))++".000Z",
  FileName = cus_util:uuid() ++ ".gif",
  Bucket = ?BUCKET_NAME,
  ACL = ?ACL,
  PolicyJson ="{\"expiration\":\""++Expiration++"\",\"conditions\":[[\"eq\",\"$bucket\",\""++Bucket++"\"],[\"eq\",\"$acl\",\""++ACL++"\"],[\"eq\",\"$key\",\""++FileName++"\"],[\"starts-with\",\"$name\",\"\"]]}",
  Policy = base64:encode(PolicyJson),
  SecretKey = ?l2b(?SECRET_KEY),
  Signature = base64:encode(crypto:hmac(sha, SecretKey, Policy)),
  Body = jsx:encode(#{
    <<"accessKey">> => ?l2b(?ACCESS_KEY),
    <<"policy">> => Policy,
    <<"signature">> => Signature,
    <<"fileName">> => ?l2b(FileName),
    <<"acl">> => ?l2b(ACL)

  }),
  echo(Body, Req);


maybe_echo(<<"POST">>, false, Req) ->
  cowboy_req:reply(400, [], <<"Missing body.">>, Req);
maybe_echo(_, _, Req) ->
  %% Method not allowed.
  cowboy_req:reply(405, [], <<"405!">>, Req).


echo(undefined, Req) ->
  cowboy_req:reply(400, [], <<"System error.">>, Req);
echo(Body, Req) ->
  cowboy_req:reply(200, [
    {<<"content-type">>, <<"application/json; charset=utf-8">>}
  ], Body, Req).

